#!/bin/bash
# This script packages the directory into a tar file.
# Copyright (C) 2014 Hewlett-Packard Development Company, L.P.
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  version 2 as published by the Free Software Foundation.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

# make sure we're in a checked out git copy
if [ ! -d .git ]; then
   echo "ERROR: No Git information found. This script requires an git tree."
   exit 0
fi

# Check if SVN is available.  If not, then abort.
which git >/dev/null 2>&1
if [ $? != 0 ]; then
   echo "ERROR: git command missing."
   exit 1
fi

######################################################################
# Package things up

if [ ! -f "Makefile.conf" ]; then
   echo "ERROR: This utility must be run from the top of the fossology source tree."
   exit 1
fi

. ./utils/utils.sh

# define VERSION and COMMIT_ID
VERSION=$(eval ${VERSION_COMMAND})
VERSION="${VERSION/-rc/~rc}-1"

# COMMIT_HASH is the last revision from git info.  This is used for packaging.
COMMIT_HASH="`git show | head -1 | awk '{print substr($2,1,6)}'`"

TARBASE="fossology_$VERSION"
# Check for command-line for subversion
if [ "$1" = "-s" ]; then
   TARBASE="fossology_$VERSION-$COMMIT_HASH"
fi

echo "*** Packaging $VERSION (git $COMMIT_HASH) into $TARBASE ***"

if [ -d "../$TARBASE" ]; then
   echo "WARNING: ../$TARBASE exists, removing"
   rm -rf "../$TARBASE"
   if [ -d "../$TARBASE" ]; then
      echo "ERROR: Unable to delete ../$TARBASE, exiting."
      exit 2
   fi
fi

echo "*** Exporting git version $COMMIT_HASH to ../$TARBASE ***"
mkdir "../$TARBASE"
cp -r . "../$TARBASE"
if [ $? != 0 ]; then
   echo "ERROR: git export failed."
   exit 3
fi

# Create the tar
(
cd ..
if [ -f "$TARBASE.orig.tar.gz" ]; then
   echo "WARNING: ../$TARBASE.orig.tar.gz exists, removing"
   rm -f "$TARBASE.orig.tar.gz"
   if [ -f "$TARBASE.orig.tar.gz" ]; then
      echo "ERROR: unable to remove ../$TARBASE.orig.tar.gz, exiting."
      exit 4
   fi
fi

echo "*** Creating tar ***"
tar --anchored --exclude=\*/debian --exclude-vcs --exclude-vcs-ignores -czf "$TARBASE.orig.tar.gz" "$TARBASE"
if [ $? != 0 ]; then
   echo "ERROR: unable to create ../$TARBASE.orig.tar.gz, exiting."
   exit 4
fi
)

# Clean up
echo "*** Cleaning up ***"
rm -rf "../$TARBASE"
if [ -d "../$TARBASE" ]; then
   echo "WARNING: Unable to clean up ../$TARBASE, exiting."
   exit 5
fi

echo "*** ../$TARBASE.orig.tar.gz created successfully. ***"
